package com.king.hpeproject.constant;


import lombok.Getter;
import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * RequestWrapper Request装饰器
 * 目的：requestBody只能读取一次，过滤器读取了requestBody，使用requestWrapper继续向下传递，不影响后续业务
 *
 * @author xxx
 * @since 2025/8/12
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    /**
     * Http请求对象
     */
    private final HttpServletRequest request;
    //参数字节数组
    @Getter
    private byte[] requestBody;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    /**
     * 每次调用此方法时将数据流中的数据读取出来，然后再回填到InputStream之中
     *
     * @return ServletInputStream
     * @throws IOException IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (null == this.requestBody) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), byteArrayOutputStream);
            this.requestBody = byteArrayOutputStream.toByteArray();
        }

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}